package com.gong.suanfa.BFS;

import com.gong.suanfa.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author GongChang
 * @version 1.0
 * @date 2021/6/16 0016 9:22
 */
//二叉树层序遍历
public class Bfs {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);

        List<List<Integer>> lists = levelOrder(root);

        return;
    }

    public static List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null){
            return new ArrayList<>();
        }
        List<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        int len = 0;//队列长度

        queue.add(root);
        len++;

        while (len != 0){
            List<Integer> list = new ArrayList<>();
            //将当前队列中数据取出插入集合，并将出队列的数的子节点加入队列
            int t = len;
            for (int i = 0; i < t; i++) {
                TreeNode poll = queue.poll();len--;
                list.add(poll.val);
                if (poll.left!=null){
                    queue.add(poll.left);
                    len++;
                }
                if (poll.right != null){
                    queue.add(poll.right);
                    len++;
                }
            }
            res.add(list);
        }

        return res;
    }
}
